#include "audio.h"

#include <iostream>
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <map>

using namespace std;

/******************************************************************************
    Este namespace serve para gerenciar os sons usados no jogo
******************************************************************************/
namespace Audio {

    //Mapa dos sons
	map<string, Mix_Chunk*> m_Sons;
	typedef map<string, Mix_Chunk*>::iterator SonsIterator;

/******************************************************************************
    Carregar(chave, arquivo)
    Instancia um novo som no mapa
******************************************************************************/
	void Carregar(const char *key, const char *arquivo) {
        Mix_Chunk *chunk = Mix_LoadWAV(arquivo);
        if (chunk != NULL) {
            m_Sons[key] = chunk;
        } else {
            cout << "Erro carregando " << arquivo
                 << ". ERRO: " << Mix_GetError() << "\n";
        }
	}

/******************************************************************************
    Get(chave)
    Recupera uma imagem instanciada
******************************************************************************/
	Mix_Chunk* Get(const char *chave) {
		SonsIterator pos = m_Sons.find(chave);
		if (pos == m_Sons.end()) return NULL;
		return pos->second;
	}

/******************************************************************************
    __Descarregar(som)
    Destroi um som
******************************************************************************/
	void __Descarregar(Mix_Chunk *som) {
		Mix_FreeChunk(som);
		som = NULL;
	}

/******************************************************************************
    Descarregar(chave)
    Desroi um som e remove do mapa
******************************************************************************/
	void Descarregar(const char *chave) {
		__Descarregar(Get(chave));
		SonsIterator pos = m_Sons.find(chave);
		if (pos == m_Sons.end()) return;
		m_Sons.erase(pos);
	}

/******************************************************************************
    Play(chave)
    Toca um som previamente instanciado
******************************************************************************/
    int Play(const char *chave, int loops, int canal) {
        return Mix_PlayChannel(canal, Get(chave), loops);
    }

/******************************************************************************
    PlayMusica(chave)
    Toca uma musica de fundo
******************************************************************************/
    int PlayMusica(const char *arquivo, int loops){
        Mix_Music *mus = Mix_LoadMUS(arquivo);
        Mix_PlayMusic(mus, loops);

    }
}

